const express = require('express');
const mysql = require('mysql2');
const bcrypt = require('bcryptjs');
const jwt = require('jsonwebtoken');
const bodyParser = require('body-parser');
const cors = require('cors');
const multer = require('multer');
const path = require('path');

const app = express();
const port = 3000;

// CORS配置
const corsOptions = {
  origin: 'http://localhost:5173',
  methods: ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'],
  allowedHeaders: ['Content-Type', 'Authorization'],
  credentials: true,
  optionsSuccessStatus: 200
};

// 中间件
app.use(cors(corsOptions));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));

// 文件上传配置
const storage = multer.diskStorage({
  destination: (req, file, cb) => {
    cb(null, 'uploads/');
  },
  filename: (req, file, cb) => {
    cb(null, Date.now() + path.extname(file.originalname));
  }
});

const upload = multer({ storage: storage });

// 数据库连接
const db = mysql.createConnection({
  host: 'localhost',
  user: 'root',
  password: '123456',
  database: 'pet_adoption'
});

db.connect(err => {
  if (err) {
    console.error('数据库连接失败：', err);
    return;
  }
  console.log('数据库连接成功');
});

// JWT认证中间件
const authenticateToken = (req, res, next) => {
  const token = req.headers['authorization'];

  if (!token) {
    return res.status(403).send('访问被拒绝');
  }

  jwt.verify(token, 'your_jwt_secret', (err, user) => {
    if (err) {
      return res.status(403).send('无效的令牌');
    }
    req.user = user;
    next();
  });
};

// 用户注册
app.post('/register', async (req, res) => {
  const { username, password, email, avatar, phone, gender, address } = req.body;

  if (!username || !password || !email) {
    return res.status(400).json({ error: "用户名、密码和邮箱不能为空" });
  }

  try {
    const [existingUser] = await db.promise().query(
      'SELECT * FROM users WHERE username = ? OR email = ?',
      [username, email]
    );

    if (existingUser.length > 0) {
      return res.status(400).json({ error: "用户名或邮箱已被占用" });
    }

    const hashedPassword = await bcrypt.hash(password, 10);

    const [result] = await db.promise().query(
      'INSERT INTO users (username, password, email, phone, address) VALUES (?, ?, ?, ?, ?)',
      [username, hashedPassword, email, phone || null, address || null]
    );

    res.json({ success: true, message: "注册成功", userId: result.insertId });
  } catch (err) {
    console.error("注册失败 - 详细错误:", err);
    res.status(500).json({ error: "服务器错误，注册失败" });
  }
});

// 用户登录
app.post('/login', async (req, res) => {
  const { username, password } = req.body;

  try {
    const [user] = await db.promise().query(
      'SELECT * FROM users WHERE username = ?',
      [username]
    );

    if (user.length === 0) {
      return res.status(401).json({ error: "用户名不存在" });
    }

    const isMatch = await bcrypt.compare(password, user[0].password);
    if (!isMatch) {
      return res.status(401).json({ error: "密码错误" });
    }

    const token = jwt.sign({ userId: user[0].id }, 'your_jwt_secret', {
      expiresIn: '1h'
    });

    res.json({
      token,
      user: {
        id: user[0].id,
        username: user[0].username,
        email: user[0].email,
        avatar: user[0].avatar,
        phone: user[0].phone,
        gender: user[0].gender,
        address: user[0].address
      }
    });
  } catch (err) {
    console.error("登录失败:", err);
    res.status(500).json({ error: "服务器错误，登录失败" });
  }
});

// 获取用户资料
app.get('/profile', authenticateToken, async (req, res) => {
  try {
    const [user] = await db.promise().query(
      `SELECT 
        id, 
        username, 
        email, 
        phone, 
        COALESCE(address, '') as address 
       FROM users 
       WHERE id = ?`,
      [req.user.userId]
    );

    if (user.length === 0) {
      return res.status(404).json({ success: false, error: "用户不存在" });
    }

    res.json({
      success: true,
      data: {
        ...user[0],
        address: user[0].address || ''
      }
    });
  } catch (err) {
    console.error("获取用户信息失败:", err);
    res.status(500).json({ success: false, error: "获取用户信息失败" });
  }
});

// 更新用户资料
app.put('/profile', authenticateToken, async (req, res) => {
  const { username, email, phone, address } = req.body;
  const userId = req.user.userId;

  if (!username || !email) {
    return res.status(400).json({ success: false, error: "用户名和邮箱不能为空" });
  }

  try {
    const [existingUser] = await db.promise().query(
      `SELECT id 
       FROM users 
       WHERE (username = ? OR email = ?) 
       AND id != ?`,
      [username, email, userId]
    );

    if (existingUser.length > 0) {
      return res.status(400).json({ success: false, error: "用户名或邮箱已被占用" });
    }

    await db.promise().query(
      `UPDATE users 
       SET 
         username = ?, 
         email = ?, 
         phone = ?, 
         address = ? 
       WHERE id = ?`,
      [username, email, phone || null, address || null, userId]
    );

    const [updatedUser] = await db.promise().query(
      `SELECT 
         id, 
         username, 
         email, 
         phone, 
         address 
       FROM users 
       WHERE id = ?`,
      [userId]
    );

    res.json({
      success: true,
      data: updatedUser[0]
    });
  } catch (err) {
    console.error("更新用户资料失败:", err);
    res.status(500).json({ success: false, error: "更新用户资料失败" });
  }
});

// 上传头像
app.post('/upload-avatar', authenticateToken, upload.single('avatar'), async (req, res) => {
  try {
    const userId = req.user.userId;
    const avatarUrl = `http://localhost:3000/uploads/${req.file.filename}`;

    await db.promise().query(
      'UPDATE users SET avatar = ? WHERE id = ?',
      [avatarUrl, userId]
    );

    res.json({ avatarUrl });
  } catch (err) {
    console.error("上传头像失败:", err);
    res.status(500).json({ error: "上传头像失败" });
  }
});

// 帖子相关路由
app.get('/posts', async (req, res) => {
  try {
    const [posts] = await db.promise().query(
      'SELECT * FROM posts ORDER BY date DESC'
    );
    res.json(posts);
  } catch (err) {
    console.error("获取帖子失败:", err);
    res.status(500).json({ error: "获取帖子失败" });
  }
});

app.get('/posts/:id', async (req, res) => {
  try {
    const [post] = await db.promise().query(
      'SELECT * FROM posts WHERE id = ?',
      [req.params.id]
    );

    if (post.length === 0) {
      return res.status(404).json({ error: "帖子不存在" });
    }

    res.json(post[0]);
  } catch (err) {
    console.error("获取帖子详情失败:", err);
    res.status(500).json({ error: "获取帖子详情失败" });
  }
});

app.post('/posts', authenticateToken, async (req, res) => {
  const { title, content } = req.body;

  if (!title || !content) {
    return res.status(400).json({ error: "标题和内容不能为空" });
  }

  try {
    const [user] = await db.promise().query(
      'SELECT username FROM users WHERE id = ?',
      [req.user.userId]
    );

    if (user.length === 0) {
      return res.status(404).json({ error: "用户不存在" });
    }

    const result = await db.promise().query(
      'INSERT INTO posts (title, content, author, date, likes, comments) VALUES (?, ?, ?, NOW(), 0, 0)',
      [title, content, user[0].username]
    );

    const newPostId = result[0].insertId;
    const [newPost] = await db.promise().query(
      'SELECT * FROM posts WHERE id = ?',
      [newPostId]
    );

    res.status(201).json(newPost[0]);
  } catch (err) {
    console.error("创建帖子失败:", err);
    res.status(500).json({ error: "创建帖子失败" });
  }
});

app.delete('/posts/:id', authenticateToken, async (req, res) => {
  try {
    const [post] = await db.promise().query(
      'SELECT * FROM posts WHERE id = ?',
      [req.params.id]
    );

    if (post.length === 0) {
      return res.status(404).json({ error: "帖子不存在" });
    }

    const [user] = await db.promise().query(
      'SELECT username FROM users WHERE id = ?',
      [req.user.userId]
    );

    if (user.length === 0 || user[0].username !== post[0].author) {
      return res.status(403).json({ error: "无权删除此帖子" });
    }

    await db.promise().query(
      'DELETE FROM posts WHERE id = ?',
      [req.params.id]
    );

    res.json({ success: true, message: "帖子删除成功" });
  } catch (err) {
    console.error("删除帖子失败:", err);
    res.status(500).json({ error: "删除帖子失败" });
  }
});

// 获取帖子评论
app.get('/posts/:id/comments', async (req, res) => {
  try {
    const [comments] = await db.promise().query(
      'SELECT * FROM comments WHERE post_id = ? ORDER BY date DESC',
      [req.params.id]
    );
    res.json(comments);
  } catch (err) {
    console.error("获取评论失败:", err);
    res.status(500).json({ error: "获取评论失败" });
  }
});

// 提交新评论
app.post('/posts/:id/comments', authenticateToken, async (req, res) => {
  const { content } = req.body;
  const postId = req.params.id;
  const userId = req.user.userId;

  try {
    // 获取用户名
    const [user] = await db.promise().query(
      'SELECT username FROM users WHERE id = ?',
      [userId]
    );
    const username = user[0].username;

    // 插入评论
    await db.promise().query(
      'INSERT INTO comments (post_id, content, author, date) VALUES (?, ?, ?, NOW())',
      [postId, content, username]
    );

    // 更新帖子评论数
    await db.promise().query(
      'UPDATE posts SET comments = comments + 1 WHERE id = ?',
      [postId]
    );

    res.json({ success: true });
  } catch (err) {
    console.error("提交评论失败:", err);
    res.status(500).json({ error: "提交评论失败" });
  }
});

// 点赞处理路由 - 使用app.route处理不同方法
app.route('/posts/:id/like')
  .post(authenticateToken, async (req, res) => {
    const postId = req.params.id;
    const userId = req.user.userId;

    try {
      // 检查是否已点赞
      const [existingLike] = await db.promise().query(
        'SELECT * FROM likes WHERE post_id = ? AND user_id = ?',
        [postId, userId]
      );

      if (existingLike.length > 0) {
        return res.status(400).json({ error: "已经点赞过该帖子" });
      }

      // 添加点赞
      await db.promise().query(
        'INSERT INTO likes (post_id, user_id) VALUES (?, ?)',
        [postId, userId]
      );

      await db.promise().query(
        'UPDATE posts SET likes = likes + 1 WHERE id = ?',
        [postId]
      );

      // 返回新的点赞数
      const [post] = await db.promise().query(
        'SELECT likes FROM posts WHERE id = ?',
        [postId]
      );
      res.json({ newLikes: post[0].likes });
    } catch (err) {
      console.error("点赞处理失败:", err);
      res.status(500).json({ error: "点赞处理失败" });
    }
  })
  .delete(authenticateToken, async (req, res) => {
    const postId = req.params.id;
    const userId = req.user.userId;

    try {
      // 检查是否已点赞
      const [existingLike] = await db.promise().query(
        'SELECT * FROM likes WHERE post_id = ? AND user_id = ?',
        [postId, userId]
      );

      if (existingLike.length === 0) {
        return res.status(400).json({ error: "尚未点赞该帖子" });
      }

      // 取消点赞
      await db.promise().query(
        'DELETE FROM likes WHERE post_id = ? AND user_id = ?',
        [postId, userId]
      );

      await db.promise().query(
        'UPDATE posts SET likes = likes - 1 WHERE id = ?',
        [postId]
      );

      // 返回新的点赞数
      const [post] = await db.promise().query(
        'SELECT likes FROM posts WHERE id = ?',
        [postId]
      );
      res.json({ newLikes: post[0].likes });
    } catch (err) {
      console.error("取消点赞失败:", err);
      res.status(500).json({ error: "取消点赞失败" });
    }
  });

// 检查点赞状态（GET请求）
app.get('/posts/:id/like', authenticateToken, async (req, res) => {
  const postId = req.params.id;
  const userId = req.user.userId;

  try {
    const [like] = await db.promise().query(
      'SELECT * FROM likes WHERE post_id = ? AND user_id = ?',
      [postId, userId]
    );
    res.json({ liked: like.length > 0 });
  } catch (err) {
    console.error("检查点赞状态失败:", err);
    res.status(500).json({ error: "检查点赞状态失败" });
  }
});


// 提交领养申请
app.post('/adopt', authenticateToken, async (req, res) => {
  const { petId, formData } = req.body;
  const userId = req.user.userId;

  try {
    const [pet] = await db.promise().query(
      'SELECT * FROM pets WHERE id = ?',
      [petId]
    );

    if (pet.length === 0) {
      return res.status(404).json({ error: "宠物不存在" });
    }

    if (pet[0].adopted) {
      return res.status(400).json({ error: "该宠物已被领养" });
    }

    await db.promise().query(
      'INSERT INTO pet_adoptions (pet_id, user_id, form_data) VALUES (?, ?, ?)',
      [petId, userId, JSON.stringify(formData)]
    );

    await db.promise().query(
      'UPDATE pets SET adopted = TRUE WHERE id = ?',
      [petId]
    );

    res.json({ success: true, message: "领养申请已提交" });
  } catch (err) {
    console.error("提交领养申请失败:", err);
    res.status(500).json({ error: "提交领养申请失败" });
  }
});

// 获取领养进度
app.get('/adoption-progress', authenticateToken, async (req, res) => {
  const userId = req.user.userId;

  try {
    const [adoptions] = await db.promise().query(
      `SELECT 
        pa.*, 
        p.id as pet_id, 
        p.name as pet_name, 
        p.image as pet_image
      FROM pet_adoptions pa
      LEFT JOIN pets p ON pa.pet_id = p.id
      WHERE pa.user_id = ?`,
      [userId]
    );

    // 格式化返回数据
    const formatted = adoptions.map(adopt => ({
      id: adopt.id,
      pet: {
        id: adopt.pet_id,
        name: adopt.pet_name,
        image: adopt.pet_image
      },
      status: adopt.status,
      current_step: adopt.current_step,
      created_at: adopt.created_at,
      updated_at: adopt.updated_at,
      notes: adopt.notes
    }));

    res.json(formatted);
  } catch (err) {
    console.error("获取领养进度失败:", err);
    res.status(500).json({ error: "获取领养进度失败" });
  }
});

// 重置领养状态
app.post('/reset-adoptions', authenticateToken, async (req, res) => {
  const userId = req.user.userId;

  try {
    const [user] = await db.promise().query(
      'SELECT is_admin FROM users WHERE id = ?',
      [userId]
    );

    if (!user[0].is_admin) {
      return res.status(403).json({ error: "无权重置领养状态" });
    }

    await db.promise().query('UPDATE pets SET adopted = FALSE');
    await db.promise().query('DELETE FROM pet_adoptions');

    res.json({ success: true, message: "领养状态已重置" });
  } catch (err) {
    console.error("重置领养状态失败:", err);
    res.status(500).json({ error: "重置领养状态失败" });
  }
});

// 获取宠物列表
app.get('/pets', async (req, res) => {
  try {
    const { type, age, gender, size, healthStatus, vaccinated, sterilized } = req.query;

    let query = 'SELECT * FROM pets WHERE adopted = FALSE';
    const params = [];

    if (type) {
      query += ' AND type = ?';
      params.push(type);
    }

    if (age) {
      query += ' AND age = ?';
      params.push(age);
    }

    if (gender) {
      query += ' AND gender = ?';
      params.push(gender);
    }

    if (size) {
      query += ' AND size = ?';
      params.push(size);
    }

    if (healthStatus) {
      query += ' AND healthStatus = ?';
      params.push(healthStatus);
    }

    if (vaccinated) {
      query += ' AND vaccinated = ?';
      params.push(vaccinated);
    }

    if (sterilized) {
      query += ' AND sterilized = ?';
      params.push(sterilized);
    }

    const [pets] = await db.promise().query(query, params);
    res.json(pets);
  } catch (err) {
    console.error("获取宠物列表失败:", err);
    res.status(500).json({ error: "获取宠物列表失败" });
  }
});

// 启动服务器
app.listen(port, () => {
  console.log(`服务器运行在 http://localhost:${port}`);
});